﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Xml.Serialization;
using Seagull.Model;
using System.Linq;

namespace Seagull.Configuration
{
    public class ChannelConfig
    {
        private List<ChannelInfo> _channels;

        [XmlArray("通道列表")]
        [XmlArrayItem("通道")]
        public List<ChannelInfo> Channels
        {
            get { return _channels; }
            set
            {
                if (!Config.SupressValidation)
                {
                    Validate(value);
                }
                _channels = value;
            }
        }

        [XmlIgnore]
        public ChannelInfo this[byte channel]
        {
            get { return Channels.FirstOrDefault(c => c.Number == channel); }
        }

        public ChannelConfig()
        {
            _channels = new List<ChannelInfo>();
        }

        public bool HasChannel(byte channel)
        {
            return this[channel] != null;
        }

        public void ForAllChannels(Action<byte> actionOnChannel)
        {
            foreach (var channelNumber in ChannelNumbers)
            {
                actionOnChannel(channelNumber);
            }
        }

        public void Validate()
        {
            Validate(Channels);
        }

        internal void Validate(List<ChannelInfo> channelInfos)
        {
            if(channelInfos.GroupBy(c => c.Number).Count() != channelInfos.Count)
            {
                throw new ConfigurationErrorsException("通道号存在重复！");
            }
        }

        public byte Count
        {
            get { return (byte) Channels.Count; }
        }

        public IEnumerable<byte> ChannelNumbers
        {
            get { return Channels.Select(t => t.Number); }
        }
    }
}
